package com.zone.api.http

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zone.api.model.ApiResponse
import org.jetbrains.anko.toast
import retrofit2.HttpException

/**
 *Author: last
 *Time: 2024/1/13
 *Description: xxx
 */
class AppHttpExceptionHandler(private val context: Context) : HttpExceptionHandler {

    private val default = DefaultHttpExceptionHandler(context)
    override fun handleException(throwable: Throwable) {

        if (throwable is HttpException) {
            if (throwable.code() == 401) {
                context.toast("登录已过期")
                return
            }
            val msg = throwable.response()?.errorBody()?.string()
            try {
                val response = Gson().fromJson<ApiResponse<String>>(
                    msg,
                    object : TypeToken<ApiResponse<String>>() {}.type
                )
                response.message?.let {
                    context.toast(it)
                }
            } catch (e: Exception) {
                default.handleException(throwable)
            }
            return
        }

        default.handleException(throwable)
    }
}